class Usergroup < ActiveRecord::Base

	def self.updateDb(groupId, newMember)
		users = User.find(:all)
		ugroups = Usergroup.find(:all, :conditions => ["group_id = ?", groupId])
		users.each{|user|
			if newMember.nil?
				ugroup = memberExist(ugroups, user.id)
					if !ugroup.nil?
						ugroup.delete
					end
			else
				if newMember[user.login].nil?
					ugroup = memberExist(ugroups, user.id)
					if !ugroup.nil?
						ugroup.delete
					end
				else
					ugroup = memberExist(ugroups, user.id)
					if ugroup.nil?
						ugroup = Usergroup.new(:group_id => groupId, :user_id => user.id).save
					end
			
				end
			end
		}
	end
	def self.memberExist(ugroups, userId)
		ugroups.each{|ugroup|
			return ugroup if ugroup.user_id == userId
		}
		return nil
	end
	
	def self.getGroupMembers(users,ugroups)
		hMember = Hash.new()
		p ugroups
		p users
		users.each{|user|
			member = false
			ugroups.each{|ugroup|
				member = true if ugroup.user_id == user.id
			}
			hMember[user.id] = member
		}
		return hMember
	end
	
	def self.isadmingroup(userId)
  		group = Group.find(:first, :conditions => ["name = 'admin' "] )
  		if Usergroup.find(:all, :conditions => ["group_id = ? and user_id = ?", group.id, userId]).length > 0 then
  			return true
  		end
  		return false
  	end
end
